﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using DHJ.Cost.Models;
using DHJ.Cost.Tasks.Dto;
using Microsoft.EntityFrameworkCore;

namespace DHJ.Cost.Tasks
{
    public class TaskAppService : CostAppServiceBase, ITaskAppService
    {
        private readonly IRepository<Task, long> _taskRepository;
        private readonly IRepository<Pici, int> _piciRepository;

        public TaskAppService(IRepository<Task, long> taskRepository, IRepository<Pici, int> piciRepository)
        {
            _taskRepository = taskRepository;
            _piciRepository = piciRepository;
        }

        public async System.Threading.Tasks.Task<PagedResultDto<SimpleTaskDto>> GetTaskByPici(GetTasksByPiciInput input)
        {
            var pici = await _piciRepository.GetAsync(input.PiciId);

            if (pici == null) throw new UserFriendlyException("查询批次出错");

            var taskPrefixs = new List<string>();

            if (!pici.TaskPrefixes.IsNullOrWhiteSpace())
            {
                taskPrefixs.AddRange(pici.TaskPrefixes.Split(','));
            }

            var query = _taskRepository.GetAll().Where(e => taskPrefixs.Any(s => e.TaskNum.StartsWith(s)))
                .WhereIf(!input.Filter.IsNullOrWhiteSpace(), e => e.TaskNum.Contains(input.Filter) || e.ProductId.Contains(input.Filter));

            var totalCount = query.Count();

            var tasks = await query
                .OrderBy(input.Sorting)
                .PageBy(input)
                .ToListAsync();

            return new PagedResultDto<SimpleTaskDto>(totalCount, ObjectMapper.Map<List<SimpleTaskDto>>(tasks));

        }
    }
}
